/*
 * @Author: huangyingli
 * @Date: 2022-10-20 15:00:19
 * @LastEditors: huangyingli
 * @LastEditTime: 2022-12-13 15:27:09
 * @Description:
 */
const express = require('express');
const fs = require('fs');

const formidable = require('express-formidable');
const { v4: uuidv4 } = require('uuid');

const { resError, resSuccess } = require('./utils/response');
const mysql = require('mysql');
const connection = mysql.createConnection({
  host: '127.0.0.1',
  user: 'root',
  port: 3306,
  password: '123',
  database: 'mycms',
});

connection.connect();

let app = express();

app.use(
  formidable({
    uploadDir: './uploadFile',
  })
);
//设置允许跨域访问该服务.
app.all('*', function (req, res, next) {
  res.header('Accept-Ranges', 'bytes');
  res.header('Access-Control-Allow-Origin', '*');
  res.header('Access-Control-Allow-Headers', '*');
  res.header('Access-Control-Allow-Methods', '*');
  res.header('Access-Control-Expose-Headers', '*');
  res.header('Content-Type', 'application/json;charset=utf-8');
  next();
});

app.listen(8088, function () {
  console.log('http://localhost:8088');
});

const {
  searchSiteConfig,
  setSiteConfig,
  getModalMange,
  setModalManage,
  getColumnManage,
  getContentManage,
  getPageConfigByModal,
  getContentData,
  setColumnManage,
  setContentData,
  getManagerList,
  setManagerList,
  createTableFromConfig,
  getComponentsByIds,
  getColumnByRoute,
} = require('./sql/site-config/search');
const { resolve } = require('path');
const path = require('path');

app.get('/site-config', (req, res) => {
  searchSiteConfig(connection, (result) => {
    console.log(result);

    res.send(result);
  });
});

app.get('/upload-file/:fileName', (req, res) => {
  const { fileName } = req.params;
  console.log(fileName);
});

app.post('/site-config', (req, res) => {
  console.log(req.fields);
  setSiteConfig(connection, req.fields, (result) => {
    res.send(result);
  });
});

app.get('/modal-manage', (req, res) => {
  getModalMange(connection, (result) => {
    res.send(result);
  });
});

app.post('/modal-manage', (req, res) => {
  let query = req.query;
  let isAdd = !req.fields.id;
  console.log(req.query, req.fields);
  setManagerList(connection, query.name, req.fields, isAdd, (result) => {
    res.send(result);
  });
});

app.get('/column-manage', (req, res) => {
  getColumnManage(connection, (result) => {
    res.send(result);
  });
});

app.post('/column-manage', (req, res) => {
  let query = req.query;
  let isAdd = !req.fields.id;
  console.log(req.query, req.fields);
  setManagerList(connection, query.name, req.fields, isAdd, (result) => {
    fs.readFile('./template/index.vue', (err, data) => {
      let template = data.toString();
      let modalContent = JSON.parse(req.fields.modalContent);
      let components = [];
      modalContent.forEach((component) => {
        components.push(
          `<Custom${component.componentFile.slice(
            0,
            component.componentFile.length - 4
          )} :route="routeName" compoent-name="${component.componentName}" />`
        );
      });
      template = template.replace('$~$', components.join(' '));

      template = template.replace('$routeName$', req.fields.route);
      console.log(template);
      fs.writeFile(
        'E:\\myCode\\learnProject\\nuxt-app\\pages\\' +
          req.fields.route +
          '.vue',
        template,
        (err) => {
          console.log('err', err);
        }
      );k
    });

    res.send(result);
  });
});

app.get('/content-manage', (req, res) => {
  getContentManage(connection, (result) => {
    res.send(result);
  });
});

app.get('/getPageConfigByModal', (req, res) => {
  let query = req.query;

  getPageConfigByModal(connection, query.name, (result) => {
    res.send(result);
  });
});

app.get('/content-data', (req, res) => {
  let query = req.query;
  getContentData(
    connection,
    query.table,
    query.columnId,
    query.modalId,
    query.subName || '',
    (result) => {
      res.send(result);
    }
  );
});

app.post('/content-manage', (req, res) => {
  let query = req.query;
  let data = req.fields;
  let table = query.table;
  let id = data.id;

  console.log(query, id, data);
  setContentData(connection, table, id, data, (result) => {
    res.send(result);
  });
});

app.get('/manager-list', (req, res) => {
  let query = req.query;
  getManagerList(connection, query.name, (result) => {
    res.send(result);
  });
});

app.post('/set-component-list', (req, res) => {
  console.log('file', req.fields, req.files);
  let query = req.query;
  for (key in req.files) {
    let f = req.files[key];
    req.fields[key] = f.name;
    req.fields[key + 'Id'] = f.path.slice(f.path.lastIndexOf('_') + 1);
  }
  let isAdd = true;
  if (req.fields.componentId) {
    isAdd = false;
  } else {
    req.fields.componentId = uuidv4();
  }

  /**
   * 需要根据表名和组件配置json文件生成表
   * 1. 先解析json文件
   *    + 拿到key 和label, 分别对应key和描述
   *    + 拿到required, 对应是否为空
   *    + 需要自动创建一个id设置位主键
   * 2. 根据传入表名生成表
   */
  console.log('file', req.fields);
  fs.readFile(
    path.resolve(__dirname + '\\' + req.files.componentConfig.path),
    (err, data) => {
      console.log('data', data);
      let config = JSON.parse(data.toString());
      createTableFromConfig(
        connection,
        req.fields.componentTable,
        config,
        (result) => {
          setManagerList(
            connection,
            query.name,
            req.fields,
            isAdd,
            (result) => {
              console.log('result', result);
              /**
               * 需要将文件写入nuxt的compoent文件中
               */

              fs.copyFile(
                path.resolve(__dirname + '\\' + req.files.componentFile.path),
                'E:\\myCode\\learnProject\\nuxt-app\\components\\Custom\\' +
                  req.fields.componentFile,
                (err) => {
                  console.log('error', err);
                  res.send(result);
                }
              );
            }
          );
        }
      );
    }
  );
});

app.get('/get-components-by-ids', (req, res) => {
  let query = req.query;

  let ids = query.ids.split(',');

  getComponentsByIds(connection, ids, (result) => {
    res.send(result);
  });
});

app.get('/get-component-config', (req, res) => {
  let id = req.query.id;

  getComponentsByIds(connection, [id], (result) => {
    console.log('result', result);
    let compoent = result.data[0];
    fs.readFile(
      `./uploadFile/upload_${compoent.componentConfigId}`,
      (err, data) => {
        res.send(resSuccess(JSON.parse(data)));
      }
    );
  });
});

app.get('/get-content-data-by-route', (req, res) => {
  let route = req.query.route;
  let compoentName = req.query.compoentName;
  let subName;
  let table;
  console.log(route, compoentName);
  getColumnByRoute(connection, route, (column) => {
    let modalId = column.modal;
    let columnId = column.id;
    console.log('column', column);
    let content = JSON.parse(column.modal_content);
    console.log('content', content);
    let component = content.find((c) => c.componentName == compoentName);
    if (component) {
      subName = component.subName;
      table = component.componentTable;
    }

    console.log(component, table, columnId, modalId, subName);
    getContentData(
      connection,
      table,
      columnId,
      modalId,
      subName || '',
      (result) => {
        res.send(result);
      }
    );
  });
});
